package com.yidu.web;

import com.google.gson.Gson;
import com.yidu.web.dao.LoggerDao;
import com.yidu.web.dao.UserDao;
import com.yidu.web.listener.SpiListener;
import com.yidu.web.model.Crosstalklist;
import com.yidu.web.model.Logger;
import com.yidu.web.utils.BaseModel;
import com.yidu.web.utils.SessionTools;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 演示websocket服务器
 */
@ServerEndpoint("/webSocket/{userId}")
public class WebSocketTest {

    UserDao dao = new UserDao();
    LoggerDao loggerDao = new LoggerDao();

    @OnOpen
    public void onOpen(@PathParam("userId")String userId, Session session) throws IOException {
        System.out.println("登录账号:"+userId);
        session.getUserProperties().put("userId",userId);
        dao.updateStatus(Integer.valueOf(userId),SessionTools.STATUS_ON);
        if(SessionTools.SESSIONS.size()>=100){
            session.getAsyncRemote().sendText("ERROR:当前服务器人数已满,目前人数:"+SessionTools.SESSIONS.size());
            session.close();
        }else{

            Map<String, Object> map = new HashMap<>();
            map.put("userId", userId);
            map.put("status", SessionTools.STATUS_ON);
            Gson gson = new Gson();
            String json = gson.toJson(map);
            sendAllMessage(json);


            SessionTools.SESSIONS.put(userId,session);
        }
    }

    @OnMessage
    public void onMessage(String message,Session session)  {
        System.out.println(session.getId()+"传过来来的消息是:"+message);

        //将页面上传过来的json字符串,转成java的对象模型
        BaseModel   bm = new BaseModel();
        Gson gson = new Gson();
        bm = gson.fromJson(message,BaseModel.class);
        Integer toUserId = bm.getToUserId();//接收人的ID

        //保存信息到数据库,不管对方是否在线
        Logger logger = new Logger();
        try {
            String mess = URLEncoder.encode(bm.getMessage(),"UTF-8");
            logger.setLoggerMessage(mess);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        logger.setUserSendId(bm.getFromUserId());
        logger.setUserAcceptId(bm.getToUserId());
        logger.setLoggerState(1); //状态 已查看
        //如果是自己发给自己
        if(bm.getFromUserId()==bm.getToUserId()){

            if("笑话".equals(bm.getMessage())){
                Object[] objects = SpiListener.map.keySet().toArray();//取随机数
                Random rd = new Random();
                String flag = (String)objects[rd.nextInt(objects.length)];
                Crosstalklist crosstalklist = SpiListener.map.get(flag);
                bm.setMessage("<h1>"+crosstalklist.getCrossTalkTitle()+"<h1><p>"+crosstalklist.getCrossTalkContent()+"<p>");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("status",10);
            map.put("bm",bm);
            String json = gson.toJson(map);
            session.getAsyncRemote().sendText(json);//给自己发一条信息
            System.out.println("自己给自己发送信息");
            logger.setLoggerState(1); //状态 已查看
        }else {
            Session sessionTo = (Session) SessionTools.SESSIONS.get(toUserId + "");
            if (sessionTo != null) { //对方在线
                Map<String, Object> map = new HashMap<>();

                map.put("status", 10);
                map.put("bm", bm);

                sendMessage(map, sessionTo, session);

                logger.setLoggerState(1); //状态 已查看
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("status", 10);
                map.put("bm", bm);
                map.put("remark", "对方不在线,不能及时回复您的信息!");
                String json = gson.toJson(map);
                session.getAsyncRemote().sendText(json);
                logger.setLoggerState(0); //状态 未查看
            }
        }

        loggerDao.insert(logger) ;//保存聊天记录

    }
    //每次只要收到一个客户端发来的信息,就将这条信息发给其他session
    public void sendAllMessage(String message){
        Set<String> keys = SessionTools.SESSIONS.keySet();
        Iterator<String> ite = keys.iterator();
        while(ite.hasNext()){
            String key = ite.next();
            Session session = (Session) SessionTools.SESSIONS.get(key);
            session.getAsyncRemote().sendText(message);
        }
    }

    //发个人的信息
    public static void sendMessage(Map<String,Object> map,Session sessionTo,Session sessionFrom){
        Gson gson = new Gson();
        String json = gson.toJson(map);
        sessionTo.getAsyncRemote().sendText(json);//给对方发一条
        sessionFrom.getAsyncRemote().sendText(json);//给自己也发一条
    }

    @OnClose
    public void onClose(Session session) throws IOException {

        System.out.println("session即将关闭!");

        String userId = (String)session.getUserProperties().get("userId");
        SessionTools.SESSIONS.remove(userId);//移除掉map中的session

        dao.updateStatus(Integer.valueOf(userId),SessionTools.STATUS_OFF);

        session.close();
        //向所有的session发信息
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("status",SessionTools.STATUS_OFF);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        sendAllMessage(json);

    }

    @OnError
    public void onError(Session session,Throwable throwable) {
        System.out.println(throwable.getMessage());
        System.out.println("出错了...."+session.getId());

    }
}
